<?php


/**
 * 主要负责处理菜单项的增删改以及菜单的结构管理
 */
class Model_MenuManager {

	/**
	 * $tb_menu
	 * @var Table_Menu
	 */
	var $tb_Menu;
	
	/**
	 * $tb_PermissionGroups
	 * @var Table_PermissionGroups
	 */
	var $tb_PermissionGroups;
	
	/**
	 * $tb_Permissions
	 * @var Table_Permissions
	 */
	var $tb_Permissions;
	
	function Model_MenuManager(){
		$this->tb_Menu =& FLEA::getSingleton('Table_Menu');
		$this->tb_PermissionGroups =& FLEA::getSingleton('Table_PermissionGroups');
		$this->tb_Permissions =& FLEA::getSingleton('Table_Permissions');
	}
	
	/**
	 * 返回权限组的列表，不包括关联数据
	 * @return array
	 */
	function permissionGroupList(){
		$this->tb_PermissionGroups->clearLinks();
		return $this->tb_PermissionGroups->findAll();
	}
	
	/**
	 * 返回菜单项列表
	 * @return array
	 */
	function menuList($trad = null){
		$T = '├';
		$L = '└';
		$I = '│';
		$S = '　';
		$conditions = null;
		if($trad){
			$conditions = "menu_id != {$trad}";
		}
		$tree = $this->tb_Menu->findAll($conditions);
		$tree = array_to_tree($tree,'menu_id');
		return dumpArrayTree($tree,0,$T,$L,$I,$S);
	}
	
	/**
	 * 根据条件返回permission列表，默认返回全部permission
	 * @param int $permission_group_id
	 * @return array
	 */
	function permissionList($permission_group_id=null){
		$condition = null;
		if($permission_group_id){
			$condition = "permission_group_id = '{$permission_group_id}'";
		}
		return $this->tb_Permissions->findAll($condition);
	}
	
	/**
	 * 创建或更新一个菜单项
	 * @param array $menu
	 * @return int
	 */
	function menuCreate($menu){
		
		// 通过permission_name自动分析控制器和控制器动作
		if(isset($menu['permission_name'])){
			$arr = explode('_', $menu['permission_name']);
			$menu['action'] = $arr[count($arr)-1];
			unset($arr[count($arr)-1],$arr[0]);
			$menu['controller'] = implode('_', $arr);
		}
		
		return $this->tb_Menu->save($menu,false);
		
	}
	
	/**
	 * 删除一个菜单项
	 *
	 * @param int $menu_id
	 * @return boolin
	 */
	function menuRemove($menu_id){
		
		return $this->tb_Menu->removeByPkv($menu_id);
		
	}
	
	
}

?>